package com.voltmao.filter;

import net.sf.json.JSONSerializer;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import com.voltmao.webpro.utils.http.HttpRequestUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


@Component("sessionFilter")
public class SessionFilter implements Filter {

	private static String ContentTypeJSON = "application/json;charset=UTF-8";


	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
						 FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		String uri = req.getRequestURI();

		String username = HttpRequestUtil.getSessionAttribute(req, "username");
		String token = "token";

		// /site/mvc/path
		// /ROOT/mvc/path -> /mvc/path

		List<String> uris = new LinkedList<String>();
		uris.add("login.html");
		uris.add("ui/login.html");
		uris.add("login_dialog.html");
		uris.add("ui/index.html");
		uris.add("student/score.html");
		uris.add("student/curriculum.html");
		uris.add("student/schoolinfo.html");

		boolean matches = false;
		for (String uri0 : uris) {
			if (uri.matches(String.format("(/(\\w){1,}){0,2}/%s", uri0))) {
				matches = true;
				break;
			}
		}

		Map<String, String> retmap = new HashMap<String, String>();
		retmap.put("statusCode", "301");
		retmap.put("message", "\u4f1a\u8bdd\u8d85\u65f6\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55\u3002");
		retmap.put("navTabId", "");
		retmap.put("callbackType", "");
		retmap.put("forwardUrl", "");

		//TODO 暂时关闭过滤器
		matches = true;

		if (!matches) {

			if (StringUtils.isEmpty(username)) {
				response.setContentType(ContentTypeJSON);
				response.getWriter().write(JSONSerializer.toJSON(retmap).toString());
				response.getWriter().flush();
				return;
			}

			if (StringUtils.isEmpty(token)) {
				response.setContentType(ContentTypeJSON);
				response.getWriter().write(JSONSerializer.toJSON(retmap).toString());
				response.getWriter().flush();
				return;
			}

			matches = false;

//			for(ITSRoleResources resource : resources){
//				String reg  = String.format("(/(\\w){1,}){0,2}%s", resource.getUrl());
//				if(uri.matches(reg)){
//					matches=true;
//					break;
//				}
//			}
			matches = true;
			if (!matches) {
				response.setContentType(ContentTypeJSON);
				response.getWriter().write(JSONSerializer.toJSON(retmap).toString());
				response.getWriter().flush();
				return;
			}
		}

		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig cfg) throws ServletException {

	}

}
